# -*- coding: utf-8 -*-

import os
import random
import re
import threading
import time
from multiprocessing import Pool

import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

url = 'https://game.gtimg.cn/images/lol/act/img/js/hero/3.js?ts=2811577'


def get_all_heroes_info():
    """获取所有英雄概览数据
        :return：所有英雄信息组成的列表
    """
    url = 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?ts=2811577'
    r = requests.get(url)
    r = r.json()['hero']
    return r


class Hero:
    """
    单个英雄，多次调用不会创建多个对象
    """
    _instance = None

    def __new__(cls, info):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, info):
        self.hero_id = info['heroId']
        self.name = info['name'] + '-' + info['title']
        self.img_datas = []
        self.api = f'https://game.gtimg.cn/images/lol/act/img/js/hero/{self.hero_id}.js?ts=2811577'
        self.path = None

    def get_img_datas(self):
        """获取每个英雄的所有图片信息
        [{name:xxx,url:xxx},...]
        """
        response = requests.get(self.api)
        if response.status_code == 200:
            print(f'获取{self.name}图片信息成功！')
            imgs = response.json()['skins']
            print(f'共获取到{len(imgs)}张图片')
            for img in imgs:
                img_name = re.sub('[/:*?<>|\\\\]+', '-', img['name'])
                img_name = re.sub('"', '\'', img_name)
                if img['chromas'] == "0":
                    img_url = img['mainImg']
                else:
                    img_url = img['chromaImg']
                self.img_datas.append({'name': img_name, 'url': img_url})
        else:
            print(f'获取{self.name}图片信息失败XXXXXXXX！')

    def create_hero_dir(self, path=''):
        """创建英明名文件夹"""
        self.path = os.path.join(path, self.name)
        if not os.path.exists(self.path) and not os.path.isdir(self.path):
            os.mkdir(self.path)

    def download_imgs(self):
        """下载当前英雄的所有图片"""
        if len(self.img_datas) > 0:
            print(f'现在开始下载----{self.name}的所有图片：\n')
            threads = []
            for img in self.img_datas:
                # name = img['name']
                # url = img['url']
                # response = requests.get(url)
                # path = os.path.join(self.path, f'{name}.jpg')
                # if response.status_code == 200:
                #     data = response.content
                #     try:
                #         with open(path, 'wb') as file:
                #             file.write(data)
                #         print(f'{name} ---- 下载成功！')
                #     except:
                #         path = os.path.join(self.path, f'{name}-下载失败.txt')
                #         with open(path, 'w') as file:
                #             file.write('大概率是官网没有图片！')
                #         print(f'{name} ---- 下载失败！')
                # else:
                #     print(f'{name} ---- 请求失败！')
                # sleep_time = random.uniform(1, 2)
                # time.sleep(sleep_time)

                thread = threading.Thread(target=download_img, args=(img, self.path))
                thread.start()
                threads.append(thread)
            # 等待所有线程结束
            for thread in threads:
                thread.join()
            print(f'{self.name}的所有图片的下载任务已处理完毕！')
        else:
            print(f'没有获取到{self.name}的图片数据！')


def download_img(img, path):
    """下载一张图片"""
    name = img['name']
    url = img['url']
    response = requests.get(url)
    path = os.path.join(path, f'{name}.jpg')
    if response.status_code == 200:
        data = response.content
        try:
            with open(path, 'wb') as file:
                file.write(data)
            print(f'{name} ---- 下载成功！')
        except:
            path = os.path.join(path, f'{name}-下载失败.txt')
            with open(path, 'w') as file:
                file.write('大概率是官网没有图片！')
            print(f'{name} ---- 下载失败！')
    else:
        print(f'{name} ---- 请求失败！')
    # sleep_time = random.uniform(1, 2)
    sleep_time = 0.5
    time.sleep(sleep_time)


if __name__ == '__main__':
    datas = get_all_heroes_info()
    for data in datas:
        path = './imgs'
        my_hero = Hero(data)
        print(id(my_hero))
        my_hero.get_img_datas()
        my_hero.create_hero_dir(path)
        my_hero.download_imgs()
